<html charset=UTF-8>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<style type="text/css">
		body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
		input, button{
    margin: 0;
    padding: 3 5;
    box-sizing: content-box;
    line-height: 20px;
    height: 20px;
}
	</style>
	<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=GuqsBD9t6UukqzwGLjxlGa5RRxmWLpV5"></script>
	<title>地图找工作</title>
</head>
<body>
	<div id="allmap"></div>
	<input id="ac" style=" width:0; height0"></input><input id="pn" style=" width:0; height0"></input>
	<input id="use_ctl_loc" style=" width:0; height0"></input>
	<!-- <div style=" position: fixed; margin-left: 5px; margin-bottom: 5px; background-color: #cecece;" >
		<button id ="switch" >开启</button>
	</div> -->
</body>
</html>

<script src="https://js.51jobcdn.com/in/js/2009/jQuery.js"></script>
<script src="./area.js"></script>
<script type="text/javascript">
	
	var marks= new Array();
	addMarker = function (tips, url, lng, lat){
		var myIcon = new BMap.Icon("http://img01.51jobcdn.com/im/2009/search/baidumap/marker_red.png", new BMap.Size(20,30));
		var _pointer =  new BMap.Point(lat, lng);
		var _marker = new BMap.Marker(_pointer,{icon:myIcon});
		var label = new BMap.Label("<a href='"+url+"'  target='_blank'>" + tips + " @ " + (_map.getDistance(_spointer,_pointer)/1000).toFixed(2)+' 千米。'+"</a>" , {offset:new BMap.Size(20,-20)});
		// 自定义文本标注样式
		label.setStyle({
			color: 'blue',
			borderRadius: '5px',
			borderColor: '#ccc',
			padding: '8px',
			height: '20px',
			lineHeight: '20px',
			fontFamily: '微软雅黑'
		});
		
		_marker.setLabel(label);
		_map.addOverlay(_marker);	

		marks.push(_marker);
	}
	
	// 百度地图API功能
	var _map = new BMap.Map("allmap"); 
	var _pointer = new BMap.Point(121.009669, 31.227906);
	_map.addControl(new BMap.MapTypeControl());   //添加地图类型控件
	_map.centerAndZoom(_pointer,14);                 
	_map.enableScrollWheelZoom();
	//_map.addControl(new BMap.NavigationControl());
	var cr = new BMap.CopyrightControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT});
	_map.addControl(cr);
	
	var top_left_nav_ctl=new BMap.NavigationControl();
	_map.addControl(top_left_nav_ctl);
	var size = new BMap.Size(10, 20);
	var top_left_city_ctl = new BMap.CityListControl({
	    anchor: BMAP_ANCHOR_TOP_LEFT,
	    offset: size,
	    // 切换城市之间事件
	    // onChangeBefore: function(){
	    //    alert('before');
	    // },
	    // 切换城市之后事件
	     onChangeAfter:function(){
	       var point = _map.getCenter();
			  mk = new BMap.Marker(point);// 创建标注
			  _map.addOverlay(mk);             // 将标注添加到地图中
			  mk.enableDragging();           // 不可拖拽
			  mk.V.title ="先拖选位置, 再双击显示搜索框...";
			  mk.addEventListener("dblclick",getAttr);
				function getAttr(){
					mk.disableDragging();
					var p = mk.getPosition();       //获取marker的位置

					_spointer = p;
                    geoc.getLocation(p, function(rs){
                            var addComp = rs.addressComponents;
                            console.info("当前切换到：" + addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
                            for(var k in ro(addComp)) {
                                    var acc=cc(addComp[k]);
                                    if( acc != null ) {
                                            ac=acc;
											$("#ac").val(acc);
											$("#pn").val(1);
                                    }
                            }
                    });

                    addSwitch(p);
                    _map.addControl(top_left_nav_ctl);
                    _map.removeControl(top_left_city_ctl);
					$("#use_ctl_loc").click();
				}
	     }
	});
	
	// 添加定位控件
	/*var geolocationControl = new BMap.GeolocationControl();
	geolocationControl.addEventListener("locationSuccess", function(e){
		_spointer = e.point;
		// 定位成功事件
		var address = '';
		address += e.addressComponent.province;
		address += e.addressComponent.city;
		address += e.addressComponent.district;
		address += e.addressComponent.street;
		address += e.addressComponent.streetNumber;
		//alert("当前定位地址为：" + address);
	});
	geolocationControl.addEventListener("locationError",function(e){
		// 定位失败事件
		alert(e.message);
	});
	_map.addControl(geolocationControl);*/
	
	var geolocation = new BMap.Geolocation();
	var geoc = new BMap.Geocoder();  
	geolocation.getCurrentPosition(function(r){
		if(this.getStatus() == BMAP_STATUS_SUCCESS){
			console.info('您的位置：'+r.point.lng+','+r.point.lat);
			//r.point = _pointer;
			if(r.point.lng == 0 && r.point.lat == 0) {
            	alert("当前百度 浏览器定位api 又把我们定位到非洲了，请稍后重新刷新.....");
            	_map.centerAndZoom(r.point =new BMap.Point(116.403765, 39.914850), 5);
            }

			//r.point = _pointer//;
			_spointer = r.point;
			mk = new BMap.Marker(r.point);
			_map.addOverlay(mk);
			_map.panTo(r.point);
			geoc.getLocation(r.point, function(rs){
				var addComp = rs.addressComponents;
				console.info(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);

				for(var k in ro(addComp)) {
					var acc=cc(addComp[k]);
					if( acc != null ) {
						ac=acc;
                        $("#ac").val(acc);
                        $("#pn").val(1);
					}
				}
				
				if(typeof(jobs_helper_ver) == "undefined" || jobs_helper_ver != 2) {
					alert("当前插件"+ ((typeof(jobs_helper_ver) == "undefined")? "未安装":"已过时") + ",请重新安装,点击确定将自动带你前去下载...");
					window.open("./jobs-helper.crx","_blank")
				} 
			});  

			addSwitch(r.point);
		}
		else {
			alert('failed'+this.getStatus());
		}        
	},{enableHighAccuracy: true})
	
	
	_map.addEventListener("tilesloaded",function(){
                /* var ev = document.createEvent('HTMLEvents');
                ev.initEvent('bmap_over', false, false);
                ev.name="地图加载完成";
                document.dispatcherEvent(ev); */
    });
		
	/* var geolocationControl = new BMap.GeolocationControl();
	  geolocationControl.addEventListener("locationSuccess", function(e){
	    // 定位成功事件
	    var address = '';
	    address += e.addressComponent.province;
	    address += e.addressComponent.city;
	    address += e.addressComponent.district;
	    address += e.addressComponent.street;
	    address += e.addressComponent.streetNumber;
	    alert("当前定位地址为：" + address);
	  });
	geolocationControl.addEventListener("locationError",function(e){
	   // 定位失败事件
	   alert(e.message);
	 });
	 _map.addControl(geolocationControl); */

	
	//关于状态码
	//BMAP_STATUS_SUCCESS	检索成功。对应数值“0”。
	//BMAP_STATUS_CITY_LIST	城市列表。对应数值“1”。
	//BMAP_STATUS_UNKNOWN_LOCATION	位置结果未知。对应数值“2”。
	//BMAP_STATUS_UNKNOWN_ROUTE	导航结果未知。对应数值“3”。
	//BMAP_STATUS_INVALID_KEY	非法密钥。对应数值“4”。
	//BMAP_STATUS_INVALID_REQUEST	非法请求。对应数值“5”。
	//BMAP_STATUS_PERMISSION_DENIED	没有权限。对应数值“6”。(自 1.1 新增)
	//BMAP_STATUS_SERVICE_UNAVAILABLE	服务不可用。对应数值“7”。(自 1.1 新增)
	//BMAP_STATUS_TIMEOUT	超时。对应数值“8”。(自 1.1 新增)
	
	// 复杂的自定义覆盖物
	function addSwitch(_pointer) {
		
	    function ComplexCustomOverlay(point){
	      this._point = point;
	    }
	    ComplexCustomOverlay.prototype = new BMap.Overlay();
	    ComplexCustomOverlay.prototype.initialize = function(map){
	      this._map = map;
	      var div = this._div = document.createElement("div");
	      div.style.position = "absolute";
	      div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);
	      div.style.backgroundColor = "#8ea8e0";
	      div.style.border = "1px solid #cccccc";
		  div.style.borderRadius = "3px"; 
	      div.style.color = "white";
	      //div.style.height = "18px";
	      //div.style.lineHeight = "18px";
	      div.style.padding = "5px";
	      div.style.whiteSpace = "nowrap";
	      div.style.MozUserSelect = "none";
	      div.style.fontSize = "12px"
	      var span = this._span = document.createElement("button");
	      span.id="switch";
	      div.appendChild(span);
	      span.appendChild(document.createTextNode("找工作"));    
	      var input = this._input = document.createElement("input");
	      input.id="kwd";
	      div.appendChild(input);      
	      var swa = this._btn2 = document.createElement("button");
	      swa.id="switchPosit";
	      swa.title ="切换位置";
	      swa.appendChild(document.createTextNode("X"));
	      div.appendChild(swa);
		  
	      var that = this;
	
	      var arrow = this._arrow = document.createElement("div");
	      arrow.style.background = "url(http://map.baidu.com/fwmap/upload/r/map/fwmap/static/house/images/label.png) 0px -20px  no-repeat";
	      arrow.style.position = "absolute";
	      arrow.style.width = "11px";
	      arrow.style.height = "10px";
	      arrow.style.top = "40px";
	      arrow.style.left = "10px";
	      arrow.style.overflow = "hidden";
	      div.appendChild(arrow);
	      
		  /*
	      $(span).click (function(){
	    	  if($("#kwd").val().trim()) {
		  		$.ajax({
		  			url:"/local/job?kwd=" + encodeURIComponent($("#kwd").val().trim()) + (span.innerHTML=="停止" ? "&opt=cls":"") + "&av=" + ac ,
		  			type:"get",
		  			beforeSend:function() {
		  				console.info(this.url);
		  				if( this.url.indexOf("&opt") == -1 ) {
		  					//del uppon markers
		  					for(var mt in marks) {
		  						_map.removeOverlay(marks[mt]);
		  					}
		  					marks= new Array();
		  					inn =1;
		  					sno =0;
		  				} else {
		  					$("#kwd").blur();
		  				}
		  			},
		  			success: function(data) {
		  				if(JSON.parse(data).res == 1) {
		  					span.innerHTML= (span.innerHTML=="停止") ? "找工作":"停止";
		  				} else 
		  					alert( JSON.parse(data).res );
		  			}
		  		});
	    	  }
		  }); */
	      $(input).click(function(event) {
	    	  //console.info(event);
	    	  //$("#kwd").focus();
	    	  event.stopPropagation();
	      });
	      $(input).dblclick(function(event) {
	    	  //cconsole.info(event);
	    	  event.stopPropagation();
	      });
	      $(input).mousedown( function(event) {
	    	  //cconsole.info(event);
	    	  event.stopPropagation();
	      });
	      $(input).keydown( function(event) {
	    	  //cconsole.info(event);
	    	  event.stopPropagation();
	      });
		  $(div).click(function(event){
	    	  event.preventDefault();
              event.stopPropagation();
          });
		  $(div).dblclick(function(event){
	    	  event.preventDefault();
              event.stopPropagation();
          });
	      $(div).mousemove(function(event){
	    	  event.preventDefault();
              event.stopPropagation();
          });
		  $(div).mouseover(function(event){
	    	  event.preventDefault();
              event.stopPropagation();
			  
          });
	

	      $(swa).click(function(){		//控件切换
				if( span.innerHTML!="停止" ) {
					_map.removeOverlay(mk); //删掉搜索锚点
					_map.removeOverlay(myCompOverlay);      //删掉自定义覆盖物
					pureMarker();
					_map.removeControl(top_left_nav_ctl);
					_map.addControl(top_left_city_ctl);
				} else {
					alert("请点击停止按钮状,方能切换位置....");
				}
	      });
	
	      //_map.getPanes().labelPane.appendChild(div);
	      _map.getPanes().labelPane.appendChild(div);
		  
	      return div;
	    }
	    ComplexCustomOverlay.prototype.draw = function(){
	      var map = this._map;
	      var pixel = map.pointToOverlayPixel(this._point);
	      this._div.style.left = pixel.x + parseInt(this._arrow.style.left) -5 + "px";
	      this._div.style.top  = pixel.y - parseInt(this._arrow.style.top) - 25 + "px";
	    }
		//给自定义覆盖物添加事件            
		ComplexCustomOverlay.prototype.addEventListener = function(event,fun){
			   this._div['on'+event] = fun;
		}
	    

	    var myCompOverlay = new ComplexCustomOverlay( _pointer );
		/*		
		myCompOverlay.addEventListener("click", function(e){  
			//覆盖物阻止事件冒泡到地图上
		   e.domEvent.stopPropagation();
		   e.domEvent.cancelBubble = true;  
		});
		myCompOverlay.addEventListener("dbclick", function(e){  
			//覆盖物阻止事件冒泡到地图上
		   e.domEvent.stopPropagation();
		   e.domEvent.cancelBubble = true;  
		});
		myCompOverlay.addEventListener("mousemove", function(e){  
			//覆盖物阻止事件冒泡到地图上
		   e.domEvent.stopPropagation();
		   e.domEvent.cancelBubble = true;  
		});
		myCompOverlay.addEventListener("mouseover", function(e){  
			//覆盖物阻止事件冒泡到地图上
		   e.domEvent.stopPropagation();
		   e.domEvent.cancelBubble = true;  
		});*/
	    _map.addOverlay(myCompOverlay);
	}
	
	sno=0;
	$("body").keydown(function(e){
		
		  if(sno<= marks.length-1) {
			  if( sno == 0 ) {
				  var cpo= _map.getCenter();
				  console.info(cpo.lng +" .. " +marks[0].point.lng);
				  console.info(Math.abs(cpo.lng - marks[0].point.lng) <0.0009);
				  console.info( cpo.lat +" .. "+marks[0].point.lat );
				  console.info( Math.abs( cpo.lat - marks[0].point.lat )< 0.0009 );
				  if( Math.abs(cpo.lng - marks[0].point.lng) <0.0009 && Math.abs( cpo.lat - marks[0].point.lat )< 0.0009 ) {
					  
				  } else {
					  console.info("...............");
					  _map.panTo(marks[0].point);
					  return;
				  }
			  }
			  switch(e.keyCode){
			    case 37: //左键
			      if(sno-- ==0) {alert ("到起点了"); sno++; }  _map.panTo(marks[sno].point); break;
			    case 38: //向上键
			      break;
			    case 39: //右键
			      if(sno++ ==marks.length-1 ) { alert("到终点了"); sno--;} _map.panTo(marks[sno].point); break;
			    case 40: //向下键
			      break;
			    default:
			      break;
			  }
		  }
	});
	
	function pureMarker(){
		
		for( var i in marks) {
			_map.removeOverlay( marks[i] )
		}
	}
	/* $(document).keypress(function(e){
		if(e.ctrlKey && e.button==1){
			alert();
		}
	}); */
</script>
